﻿Imports System.Security.Cryptography
Imports System.Text

Public Class DES
    Public Function GenerateKey() As String
        Dim desCrypTo As DESCryptoServiceProvider = DESCryptoServiceProvider.Create
        Return ASCIIEncoding.ASCII.GetString(desCrypTo.Key)
    End Function
    Public Function Encrypt(ByVal pToEncrypt As String, Optional ByVal sKey As String = "12345678") As String
        Dim Des As New DESCryptoServiceProvider
        Dim InputByteArray() As Byte, KeyArray As Byte()
        InputByteArray = Encoding.Default.GetBytes(pToEncrypt)
        KeyArray = ASCIIEncoding.ASCII.GetBytes(sKey)
        ' Des.KeySize = sKey.Length
        Des.Key = KeyArray
        Des.IV = KeyArray
        Dim ms As New System.IO.MemoryStream
        Dim cs As New CryptoStream(ms, Des.CreateEncryptor, CryptoStreamMode.Write)
        cs.Write(InputByteArray, 0, InputByteArray.Length)
        cs.FlushFinalBlock()
        Dim ret As New StringBuilder
        Dim b As Byte
        For Each b In ms.ToArray
            ret.AppendFormat("{0:X2}", b)
        Next
        Return ret.ToString()
    End Function
    Public Function Decrypt(ByVal pToDecrypt As String, Optional ByVal sKey As String = "12345678") As String
        Try
            Dim des As New DESCryptoServiceProvider
            Dim len As Integer
            len = pToDecrypt.Length / 2 - 1
            If len = 0 Then len = 1
            Dim InputByteArray(len) As Byte
            Dim x, i As Integer
            For x = 0 To len
                i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)
                InputByteArray(x) = CType(i, Byte)
            Next
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
            Dim ms As New System.IO.MemoryStream
            Dim cs As New CryptoStream(ms, des.CreateDecryptor, CryptoStreamMode.Write)
            cs.Write(InputByteArray, 0, InputByteArray.Length)
            cs.FlushFinalBlock()
            Return Encoding.Default.GetString(ms.ToArray)
        Catch
            Return ""
        End Try
    End Function
End Class
